<?php
/**
 * Created by YuanXiShop.
 * User: YuanXi
 * Date: 2021/6/3 0003
 * Time: 1:26
 */

namespace admin;

use JasonGrimes\Paginator;
use lmonkey\CatTree as CT;
use models\BaseDao;
use Slince\Upload\UploadHandlerBuilder;

class Product extends Admin
{
    function __construct()
    {
        parent::__construct();
        $this->assign('menumark','product');
        //获取数据库操作对象
        $db = new BaseDao();

        //获取全部商品分类，并按ord排序
        $data = $db->select('category','*',['ORDER'=>['ord'=>'ASC','id'=>'DESC']]);

        $cats = CT::getList($data);

        //将数据分配给模板
        $this->assign('cats',$cats);
    }
    function index()
    {
        $db = new BaseDao();

        $num = $_GET['num'] ?? 1;
        //搜索条件
        $where = [];
        $prosql =[];
        if(isset($_GET['state']) && $_GET['state'] != ''){
            $where['state'] = $_GET['state'];
            $state = "&state=".$_GET['state'];
        }

        if(!empty($_GET['name'])){
            $where['name[~]'] = $_GET['name'];
            $name = '&name='.$_GET['name'];
        }
        if(!empty($_GET['cid']) || $_GET['cid'] != 0){
            $where['cid'] = $_GET['cid'];
            $cid = '&cid='.$_GET['cid'];
        }

        if(!empty($_GET['filter']) || $_GET['filter'] !='' ){
            list($filed, $value) = explode('|', $_GET['filter']);
            $where[$filed] = $value;
            $filter='&filter='.$_GET['filter'];
        }
        if(!empty($_GET['orderby']) || $_GET['orderby'] !='' ) {
            list($filed, $value) = explode('|', $_GET['orderby']);
            // $prosql['ORDER'][$filed] = [$value];
            $prosql['ORDER'][$filed] .= strtoupper($value);
            $orderby='&orderby='.$_GET['orderby'];
        }else {
            $prosql['ORDER'] = ["id" => "DESC"];
        }
        $this->assign('get',$_GET);

        $totalItems = $db->count('product',$where);//总页面数
        $itemsPerPage = PNUM;//每页显示多少条数据
        $currentPage = $num;//当前页是第几页
        $urlPattern = '/admin/product?num=(:num)'.$state.$name.$cid.$filter.$orderby;

        $paginator = new Paginator($totalItems, $itemsPerPage, $currentPage, $urlPattern);

        //从第几页开始
        $start = ($currentPage-1) * $itemsPerPage;
        $prosql['LIMIT'] = [$start,$itemsPerPage];

        $prosql = array_merge($prosql,$where);

        $data = $db->select('product','*',$prosql);

        //将数据分配给模板
        $this->assign('data',$data);
        $this->assign('fpage',$paginator);

        //过滤条件
        $filter_arr = ['istuijian|1'=>'推荐商品','istj|1'=>'特价商品','wlmoney|0'=>'包邮商品','num|0'=>'售空商品'];
        $this->assign('filter_arr',$filter_arr);

        $orderby_arr['clicknum|desc'] = '浏览量(多到少)';
        $orderby_arr['clicknum|asc'] = ' 浏览量(少到多)';
        $orderby_arr['sellnum|desc'] = '销售量(多到少)';
        $orderby_arr['sellnum|asc'] = '销售量(少到多)';
        $orderby_arr['num|desc'] = '库存量(多到少)';
        $orderby_arr['num|asc'] = '库存量(少到多)';
        $orderby_arr['collectnum|desc'] = '收藏数(多到少)';
        $orderby_arr['collectnum|asc'] = '收藏数(少到多)';
        $orderby_arr['asknum|desc'] = '咨询数(多到少)';
        $orderby_arr['asknum|asc'] = '咨询数(少到多)';
        $orderby_arr['commentnum|desc'] = '评价数(多到少)';
        $orderby_arr['commentnum|asc'] = '评价数(少到多)';

        $this->assign('orderby_arr',$orderby_arr);

        //标题
        $this->assign('title','文章列表');
        //输出模板
        $this->display('product/index');
    }
    function add()
    {
        if($_POST['do_submit']){
            $path = TEMPDIR."/uploads/product";

            $builder = new UploadHandlerBuilder(); //create a builder.
            $handler = $builder

                //add constraints

                ->allowExtensions(['jpg', 'png', 'gif'])
                ->allowMimeTypes(['image/*'])

                ->saveTo($path) //save to local
                ->getHandler();
            $files = $handler->handle();
            $filename = $files['logo']->getUploadedFile()->getClientOriginalName();

            $newfilename =  date('Y-md') . '-' . uniqid() . '.' . $files['logo']->getUploadedFile()->getClientOriginalExtension();

            rename($path.'/'.$filename, $path.'/'.$newfilename);

            $db = new BaseDao();

            unset($_POST['do_submit']);

            $_POST['logo'] = $newfilename;
            $_POST['atime'] = empty($_POST['atime']) ? time() : strtotime($_POST['atime']);
            $_POST['istj'] = isset($_POST['istj']) ? 1 : 0;

            if($db->insert('product',$_POST)){
                $this->success('/admin/product','添加成功！');
            }else{
                $this->error('/admin/product','添加失败！');
            }
        }
        $this->assign('title','文章添加');
        $this->display('product/add');
    }
    function mod($id)
    {
        $db = new BaseDao();
        $data = $db->get('product','*',['id'=>$id]);
        $this->assign($data);
        $this->assign('title','修改文章');
        $this->display('product/mod');
    }
    function doupdate()
    {
        if($_FILES['logo']['error'] == 0){
            $path = TEMPDIR."/uploads/product";

            $builder = new UploadHandlerBuilder(); //create a builder.
            $handler = $builder

                //add constraints

                ->allowExtensions(['jpg', 'png', 'gif'])
                ->allowMimeTypes(['image/*'])

                ->saveTo($path) //save to local
                ->getHandler();
            $files = $handler->handle();
            $filename = $files['logo']->getUploadedFile()->getClientOriginalName();

            $newfilename =  date('Y-md') . '-' . uniqid() . '.' . $files['logo']->getUploadedFile()->getClientOriginalExtension();

            rename($path.'/'.$filename, $path.'/'.$newfilename);

            $_POST['logo'] = $newfilename;
        }
        $id = $_POST['id'];

        unset($_POST['id']);

        $db = new BaseDao();

        $_POST['atime'] = empty($_POST['atime']) ? time() : strtotime($_POST['atime']);
        $_POST['istj'] = isset($_POST['istj']) ? 1 : 0;

        if($db->update('product',$_POST,['id'=>$id])){
            $this->success('/admin/product','修改成功！');
        }else{
            $this->error('/admin/product/mod/'.$id,'修改失败！');
        }
    }
    function del($id)
    {
        $db = new BaseDao();
        if($db->delete('product',['id'=>$id])){
            $this->success('/admin/product','删除成功！');
        }else{
            $this->error('/admin/product','删除失败！');
        }
    }
    function alldel()
    {
        $db = new BaseDao();
        $num = 0;
        foreach ($_POST['id'] as $id){
            $num += $db->delete('product',['id'=>$id]);
        }
        if($num > 0){
            $this->success('/admin/product',$num.'个商品删除成功！');
        }else{
            $this->error('/admin/product','删除失败！');
        }
    }

    function state($state)
    {
        $db = new BaseDao();
        $num = 0;
        foreach ($_POST['id'] as $id){
            $num += $db->update('product',['state'=>$state],['id'=>$id]);
        }
        $mess = ['下架','上架'];
        if($num > 0){
            $this->success('/admin/product',$num.'个商品'.$mess[$state].'成功！');
        }else{
            $this->error('/admin/product','批量'.$mess[$state].'失败！');
        }
    }

    function tuijian($tuijian)
    {
        $db = new BaseDao();
        $num = 0;
        foreach ($_POST['id'] as $id){
            $num += $db->update('product',['istuijian'=>$tuijian],['id'=>$id]);
        }
        $mess = ['取消推荐','推荐'];
        if($num > 0){
            $this->success('/admin/product',$num.'个商品'.$mess[$tuijian].'成功！');
        }else{
            $this->error('/admin/product','批量'.$mess[$tuijian].'失败！');
        }
    }
}